// 存储服务
import {MyMap} from "./lodash";


function Dao(name) {
    var Obj = AV.Object.extend(name);
    this.objName = name
    this.obj = new Obj()
    this.query = new AV.Query(name);
    var self = this

    this.select = (options) => {
        MyMap(options, function (value, key) {
            self.query.equalTo(key, value);
        })
        return self.query.find()
    }
    this.selectOne = async (options) => {
        var result = await  this.select(options)
        return result[0]
    }
    this.insert = (options) => {
        MyMap(options, function (value, key) {
            var t = /^[a-zA-Z0-9_]/;
            if (value && t.test(key) && key != 'objectId' && key != 'createdAt' && key != "updatedAt") {
                self.obj.set(key, value)
            }
        })
        return self.obj.save()
    }

    this.update = (id, options) => {
        var Obj = AV.Object.extend(this.objName);
        var obj = new Obj()
        obj.id = id
        MyMap(options, function (value, key) {
            var t = /^[a-zA-Z0-9_]/;
            if (value && t.test(key) && key != 'objectId' && key != 'createdAt' && key != "updatedAt") {
                obj.set(key, value)
            }
        })
        return obj.save()
    }
}

export default Dao